# -*- coding: utf-8 -*-

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QDialog, QListWidgetItem, QSizePolicy
from PyQt5.QtGui import QFont
from task import Task
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout, QHBoxLayout, QCheckBox
from PyQt5.QtGui import QFont, QCursor
from PyQt5.QtCore import Qt

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel

from utils import sanitize_filename


# Form implementation generated from reading ui file 'VideoSelectDialogUI.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


class Ui_Dialog(object):
    selected_videos = []
    selected_result = pyqtSignal(list, str)

    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(647, 501)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/icon/icons/youtube.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Dialog.setWindowIcon(icon)
        self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
        self.verticalLayout.setObjectName("verticalLayout")
        self.topLayout = QtWidgets.QHBoxLayout()
        self.selectAllCheckbox = QtWidgets.QCheckBox("全选")
        self.selectAllCheckbox.setCursor(QCursor(Qt.PointingHandCursor))

        # 左边是 checkbox
        self.topLayout.addWidget(self.selectAllCheckbox, alignment=Qt.AlignLeft)

        # 右边 spacer
        spacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.topLayout.addItem(spacer)

        self.verticalLayout.addLayout(self.topLayout)

        self.listWidget = QtWidgets.QListWidget(Dialog)
        self.listWidget.setObjectName("listWidget")
        self.verticalLayout.addWidget(self.listWidget)
        self.formatComboBox = QtWidgets.QComboBox(Dialog)
        self.formatComboBox.setGeometry(QtCore.QRect(100, 100, 200, 30))
        self.formatComboBox.setObjectName("ComboxBox")
        self.verticalLayout.addWidget(self.formatComboBox)
        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.verticalLayout.addWidget(self.buttonBox)

        self.retranslateUi(Dialog)
        self.buttonBox.accepted.connect(Dialog.accept)  # type: ignore
        self.buttonBox.rejected.connect(Dialog.reject)  # type: ignore
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "视频选择"))


class VideoSelectionDialog(QDialog, Ui_Dialog):
    format_set = {}

    def __init__(self, parent=None, info=None):  # ← 这里改为 __init__
        super().__init__(parent)  # ← 这里也要改为 __init__
        self.setupUi(self)
        self.title = sanitize_filename(info['title'])
        self.show_video_infos(info['entries'])
        self.show_available_formats(info['entries'])
        self.entries = info['entries']
        self.buttonBox.accepted.connect(self.handle_accept)
        self.selectAllCheckbox.stateChanged.connect(self.toggle_all_checkboxes)

    def toggle_all_checkboxes(self, state):
        is_checked = state == Qt.Checked
        for i in range(self.listWidget.count()):
            item = self.listWidget.item(i)
            if getattr(item, "checkbox", None):
                item.checkbox.setChecked(is_checked)

    def show_available_formats(self, entries):
        for entry in entries:
            formats = entry.get("formats", [])
            for fmt in formats:
                fmt_id = fmt.get("format_id")
                resolution = fmt.get("resolution") or fmt.get("height", "")
                ext = fmt.get("ext", "")
                label = f"{resolution} ({ext})"
                if fmt_id and label:
                    self.format_set[fmt_id] = label

            # 格式化后加入 ComboBox
        self.formatComboBox.clear()
        self.formatComboBox.addItem("自动选择最佳质量", userData=None)  # 默认项
        self.formatComboBox.currentIndexChanged.connect(self.on_formate_selected)
        for fmt_id, label in sorted(self.format_set.items(), key=lambda x: x[1]):
            self.formatComboBox.addItem(label, userData=fmt_id)

    from PyQt5.QtGui import QFont

    def show_video_infos(self, entries):
        self.listWidget.clear()
        self.listWidget.setStyleSheet("""
            QListWidget {
                border: none;
                background: transparent;
            }
        """)

        for entry in entries:
            widget = QWidget()
            outer_layout = QHBoxLayout(widget)
            outer_layout.setContentsMargins(10, 10, 10, 10)
            outer_layout.setSpacing(15)

            # 设置卡片风格
            widget.setStyleSheet("""
                QWidget {
                    background-color: #ffffff;
                    border: 1px solid #dddddd;
                    border-radius: 12px;
                }
                QWidget:hover {
                    background-color: #f9f9f9;
                    border: 1px solid #aaaaaa;
                }
            """)

            # 勾选框
            checkbox = QCheckBox()
            checkbox.setFixedSize(20, 20)
            checkbox.setChecked(True)
            checkbox.setCursor(QCursor(Qt.PointingHandCursor))
            outer_layout.addWidget(checkbox, alignment=Qt.AlignTop | Qt.AlignLeft)

            # 垂直内容部分
            inner_layout = QVBoxLayout()
            inner_layout.setSpacing(4)
            inner_layout.setAlignment(Qt.AlignTop | Qt.AlignLeft)

            # 标题 Label（左对齐）
            title_label = QLabel(entry.get("title", "未知标题"))
            title_font = QFont()
            title_font.setPointSize(12)
            title_font.setBold(True)
            title_label.setFont(title_font)
            title_label.setAlignment(Qt.AlignLeft)
            title_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
            inner_layout.addWidget(title_label)

            # URL Label（左对齐）
            url = f"https://www.youtube.com/watch?v={entry.get('id', '')}"
            url_label = QLabel(f'<a href="{url}">{url}</a>')
            url_label.setTextInteractionFlags(Qt.TextBrowserInteraction)
            url_label.setOpenExternalLinks(True)
            url_label.setStyleSheet("color: #1a73e8;")
            url_label.setAlignment(Qt.AlignLeft)
            url_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
            inner_layout.addWidget(url_label)

            outer_layout.addLayout(inner_layout)

            # 添加到列表
            item = QListWidgetItem(self.listWidget)
            item.setSizeHint(widget.sizeHint())
            item.setFlags(item.flags() | Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            self.listWidget.addItem(item)
            self.listWidget.setItemWidget(item, widget)

            # 存下 checkbox 和 entry 的对应关系（用于收集选中的）
            item.checkbox = checkbox

    def on_formate_selected(self, index):
        format_id = self.formatComboBox.itemData(index)
        format_text = self.formatComboBox.currentText()

        # 保存当前选中的 format_id
        self.selected_format_id = format_id

        # 查找当前 format 的详细信息（基于第一个 entry）
        if self.entries:
            formats = self.entries[0].get("formats", [])
            self.formatComboBox.setVisible(True if formats else False)
            for fmt in formats:
                if fmt.get("format_id") == format_id:
                    has_audio = fmt.get("acodec", "none") != "none"
                    resolution = f"{fmt.get('width', '?')}x{fmt.get('height', '?')}"
                    print(f"选择格式: {format_text} ({format_id})，是否有音频: {has_audio}，分辨率: {resolution}")
                    break

    def handle_accept(self):
        tasks = []
        selected_format_id = self.selected_format_id if hasattr(self, 'selected_format_id') else None

        for i in range(self.listWidget.count()):
            item = self.listWidget.item(i)
            entry = self.entries[i]

            # 检查当前视频是否被选中
            if item.checkbox.isChecked():  # 使用 item.checkbox.isChecked() 来判断
                task = Task()
                task.title = entry.get('title', '未知标题')
                video_id = entry.get('id') or entry.get('url')
                task.url = f'https://www.youtube.com/watch?v={video_id}'

                formats = entry.get('formats', [])
                chosen_format = None
                best_format = None
                best_resolution = 0

                for fmt in formats:
                    fmt_id = fmt.get("format_id")
                    if fmt_id == selected_format_id:
                        chosen_format = fmt
                    # 自动选择：找分辨率最大的 mp4 格式且带音频
                    if fmt.get("ext") == "mp4" and fmt.get("acodec", "none") != "none":
                        height = fmt.get("height", 0) or 0
                        if height > best_resolution:
                            best_resolution = height
                            best_format = fmt

                if selected_format_id and chosen_format:
                    # 检查是否含音频
                    if chosen_format.get("acodec", "none") == "none":
                        # 没音频，查找一个音频流
                        audio_format = next((f for f in formats if
                                             f.get("vcodec", "none") == "none" and f.get("acodec", "none") != "none"),
                                            None)
                        if audio_format:
                            task.format = f"{selected_format_id}+{audio_format.get('format_id')}"
                        else:
                            task.format = selected_format_id  # 找不到音频流也照样用
                    else:
                        task.format = selected_format_id
                else:
                    # 自动选择逻辑
                    if best_format:
                        task.format = best_format.get("format_id")
                    else:
                        task.format = 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best'  # 最后兜底

                tasks.append(task)

        # 将选中的任务传递出去
        self.selected_result.emit(tasks, self.title)
        self.accept()  # 正常关闭对话框


